#!/usr/bin/env python
# -*- coding: utf-8 -*-
# time: 2022/10/19 15:11
# file: user.py
# author: lotus163
from fastapi import APIRouter, Depends, File

from backend.core.custom_exc import LoginException
from backend.core.deps import UserDepends, get_user_depends
from backend.core.result import Result, ResultUseProfile, result_success
from backend.core.security import verify_password, hash_password
from backend.crud import UserDao
from backend.schemas import SysUserSch
from backend.service.system.user import UserService

router = APIRouter(prefix="/profile", tags=["个人信息"])


@router.get("", response_model=ResultUseProfile, summary='获取个人信息')
async def get_profile(user_depends: UserDepends = Depends(get_user_depends)):
    user_db = await UserDao.get_db_or_none(userId=user_depends.login_user.user.userId)
    user_all_sch = await UserService().get_user_all_sch_by_db(user_db)
    return result_success(data=user_all_sch, postGroup="董事长", roleGroup="超级管理员")


@router.put("", response_model=Result, summary='修改个人信息')
async def update_profile(form: SysUserSch, user_depends: UserDepends = Depends(get_user_depends)):
    user_db = await UserDao.get_db_or_none(userId=form.userId)
    form.updateBy = user_depends.login_user.user.userName
    await UserDao.update_sch(user_db, **form.dict(exclude_none=True))
    return result_success()


@router.post("/avatar", response_model=Result, summary='头像上传')
async def upload_avatar(avatarfile: bytes = File(...), user_depends: UserDepends = Depends(get_user_depends)):
    file_name = user_depends.login_user.user.userName + ".jpg"
    file_path = "./static/" + file_name
    # with open(file_path,"wb") as f:
    #     f.write(avatarfile)
    return result_success()


@router.put("/updatePwd", response_model=Result, summary='重置密码')
async def update_password(oldPassword: str, newPassword: str, user_depends: UserDepends = Depends(get_user_depends)):
    user_db = await UserDao.get_db_or_none(userId=user_depends.login_user.user.userId)
    # 验证密码
    if not verify_password(oldPassword, user_db.password):
        raise LoginException("旧密码错误")
    await UserDao.update_sch(user_db, password=hash_password(newPassword))
    return result_success()
